package com.lst.httpsRequest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.log4j.Logger;

import com.lst.common.CommonHttpsUrl;
import com.lst.model.CommonKV;
import com.lst.httpService.ICallWebService;

public class HttpsCtrl implements ICallWebService {
	protected static Logger log = Logger.getLogger("log");

	public String getWebServiceResult(String url) {
		try {
			URL reqURL = new URL(url);

			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { new MyX509TrustManager() }, new java.security.SecureRandom());

			HttpsURLConnection httpsConn = (HttpsURLConnection) reqURL.openConnection();
			httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
			httpsConn.setHostnameVerifier(new MyHostnameVerifier());
			httpsConn.setRequestMethod("POST");
			httpsConn.setDoOutput(true);
			httpsConn.setConnectTimeout(20000);

			BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));

			String temp = in.readLine();
			String result = null;
			while (temp != null) {
				if (result != null)
					result += temp;
				else
					result = temp;
				temp = in.readLine();
			}
			result = URLDecoder.decode(result, "UTF-8");
			return result;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return "";
		}
	}

	private class MyX509TrustManager implements X509TrustManager {
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	}

	private class MyHostnameVerifier implements HostnameVerifier {
		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

	public String returnParam(Object obj, String reflectClass) {
		try {
			Field[] commField = Class.forName("com.lotusoftec.model.CommonPara").getDeclaredFields();
			List<CommonKV> ltCommomKV = new ArrayList<CommonKV>();

			CommonKV commonKv = null;
			for (int i = 0; i < commField.length; i++) {
				commonKv = new CommonKV();
				commonKv.setCommonKey(commField[i].getName());
				commonKv.setCommonValue(commField[i].get(obj).toString());

				ltCommomKV.add(commonKv);
			}

			Field[] modelFds = Class.forName("com.lotusoftec.model.SearchResult").getDeclaredFields();

			for (int i = 0; i < modelFds.length; i++) {
				if (modelFds[i].get(obj) == null) {
					continue;
				}

				commonKv = new CommonKV();
				commonKv.setCommonKey(modelFds[i].getName());
				commonKv.setCommonValue(modelFds[i].get(obj).toString());

				ltCommomKV.add(commonKv);
			}

			Collections.sort(ltCommomKV);

			String param = "";
			String param4Md5 = "";
			for (CommonKV commonKV : ltCommomKV) {
				param += commonKV.commonKey + "=" + URLEncoder.encode(commonKV.commonValue, "UTF-8") + "&";
				param4Md5 += commonKV.commonValue + "|";
			}
			param4Md5 = param4Md5 + CommonHttpsUrl.PARTER_PRIVATE_KEY;
			param += "sign=" + MD5Util.encrypByMd5(param4Md5);
			return param;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return "";
		}
	}
}
